//
//  NewsCommentViewController.m
//  SportSocial
//
//  Created by yull on 15/1/5.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#define NEWS_COMMENT_COUNT 10

#import "NewsCommentViewController.h"
#import "NewsNet.h"
#import "NewsComment.h"
#import "NewsCommentCell.h"
#import "UIScrollView+PullToRefresh.h"
#import "UserInfoViewController.h"

@interface NewsCommentViewController () <UITableViewDataSource,UITableViewDelegate,NewsCommentCellDelegate>

@property (nonatomic, strong) UITableView *commentTableView;

@property (nonatomic, strong) NSMutableArray *commentArray;

@property (nonatomic, assign) UInt64 newsId;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation NewsCommentViewController

- (instancetype)initWithNewsId:(UInt64)newsId
{
    if (self = [super init]) {
        self.newsId = newsId;
        self.pageNum = 0;
        
        self.commentArray = [NSMutableArray array];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"评论";
    
    [self addCommonBackButton];
    
    self.commentTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - Navibar_Height) style:UITableViewStylePlain];
    self.commentTableView.dataSource = self;
    self.commentTableView.delegate = self;
    self.commentTableView.backgroundColor =[UIColor clearColor];
    self.commentTableView.separatorInset = UIEdgeInsetsZero;
    [self.view addSubview:self.commentTableView];
    
    self.commentTableView.tableFooterView = [[UIView alloc] init];
    
    [self loadNewsCommentFromServer];
    
    [self addRefreshAndLoadMore];
}

- (void)addRefreshAndLoadMore
{
    @weakify(self);
    [self.commentTableView nd_addPullToRefreshWithActionHandler:^(id sender) {
        @strongify(self);
        self.pageNum = 0;
        [self.commentArray removeAllObjects];
        [self loadNewsCommentFromServer];
    } loadMoreWithActionHandler:^(id sender) {
        @strongify(self);
        [self loadNewsCommentFromServer];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.commentArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsComment *comment = [self.commentArray objectAtIndex:indexPath.row];
    return [NewsCommentCell calculateCommentHeight:comment.comment];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"CommentCell";
    NewsCommentCell *commentCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!commentCell) {
        commentCell = [[NewsCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        commentCell.delegate = self;
    }
    NewsComment *comment = [self.commentArray objectAtIndex:indexPath.row];
    [commentCell drawCellWithComment:comment];
    return commentCell;
}

- (void)loadNewsCommentFromServer
{
    @weakify(self);
    [NewsNet getNewsCommentWithNewsId:self.newsId pageNum:self.pageNum+1 pageSize:NEWS_COMMENT_COUNT successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dataDict = [responseObject objectForKey:@"data"];
            self.pageNum = [[dataDict objectForKey:@"pageNumber"] integerValue];
            
            NSArray *listArray = [dataDict objectForKey:@"list"];
            
            for (NSDictionary *commentDict in listArray) {
                [self.commentArray addObject:[NewsComment newsCommentWithDict:commentDict]];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.commentTableView reloadData];
                [self endLoad];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
                [self endLoad];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
            [self endLoad];
        });
    }];
}

- (void)endLoad
{
    [self.commentTableView nd_endRefreshing];
    [self.commentTableView nd_endLoadMore];
}

#pragma mark - NewsCommentCellDelegate
- (void)onHeadImageClick:(NewsComment *)comment
{
    if ([CurrentUser shareInstance].token && comment.user_id != [CurrentUser shareInstance].userId) {
        UIViewController *infoViewController = [Interface createUserInfoViewControllerWithUserId:comment.user_id userName:comment.user_name];
        [self.navigationController pushViewController:infoViewController animated:YES];
    }
}
@end
